package com.qire.manhua.dialog;

import android.app.Activity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;

import com.qire.common.support.base.BaseDialog;
import com.qire.common.utils.SVGAPlayUtil;
import com.qire.manhua.R;
import com.qire.manhua.databinding.DialogComicReaderLoadBinding;

import androidx.annotation.NonNull;
import androidx.databinding.ObservableInt;

/**
 * 漫画阅读器加载弹窗：启动阅读器时遮罩页面，并给定缓冲时间
 */
public class ComicReaderLoadDialog extends BaseDialog {

    private final DialogComicReaderLoadBinding viewDataBinder;

    public final ObservableInt maxProgress = new ObservableInt(100);
    public final ObservableInt progress = new ObservableInt(0);

    public ComicReaderLoadDialog(@NonNull Activity activity) {
        super(activity, R.style.AppTheme_FullScreen);
        setOwnerActivity(activity);
        viewDataBinder = DialogComicReaderLoadBinding.inflate(LayoutInflater.from(activity), null,false);
        viewDataBinder.setComicReaderLoadDialog(this);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(viewDataBinder.getRoot());
        setCancelable(false);
    }

    @Override
    public void show() {
        super.show();
        viewDataBinder.loadOwlSVGA.post(this::playAnimator);
        progressRun();
    }

    private void playAnimator() {
        new SVGAPlayUtil(viewDataBinder.loadOwlSVGA)
                .addSVGAPath("svga/read_owl_a.svga", 1)
                .addSVGAPath("svga/read_owl_b.svga")
                .startAnimator();
    }

    private void progressRun() {
        int p = progress.get();
        progress.set(p + 5);
        if(p < 100) {
            viewDataBinder.getRoot().postDelayed(this::progressRun, 500);
        } else {
            dismiss();
        }
    }

    public void closeBtnOnClick(View view) {
        dismiss();
        getOwnerActivity().finish();
    }

}
